package notes.java.concurrent;

import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 模拟 在一家餐厅吃饭，共10个人，都到了再开始吃饭
 * CountDownLatch实现
 * @author wangcs
 *
 */
public class U11_TestCyclicBarrier3 {

	// 人数10
	private static int totalPeople = 10;
	// 等待的限制
	private static CountDownLatch latch = new CountDownLatch(totalPeople);
	
	public static void main(String[] args) throws InterruptedException {
		// 定义线程池
		ExecutorService executor = Executors.newCachedThreadPool();
		// 起10个线程，代表10个人
		for(int i=0; i<totalPeople; i++) {
			int threadNum = i;
			executor.execute(()-> {
				// 等吃饭的事件
				try {
					eat(threadNum);
					latch.countDown();
				} catch (Exception e) {
					e.printStackTrace();
				}
			});
		}
		latch.await();
		System.out.println("都到齐了，可以吃了");
		executor.shutdown();
	}
	
	private static void eat(int threadNum) throws Exception{
		// 模拟每个人等待时间不一样
		Thread.sleep(threadNum*1000);
		System.out.println(threadNum + "我到了" + new Date());
	}
}
